package org.magnerfuller.imtoolkit.util;

import java.io.*;
import java.util.Vector;

public class LazyReader extends Thread {

  protected BufferedReader reader;
  
  protected Vector<LazyReaderListener> listeners;
  
  public LazyReader(InputStream stream) {
    super();
    reader = new BufferedReader(new InputStreamReader(stream));
    listeners = new Vector<LazyReaderListener>();
  }
  
  public void addListener(LazyReaderListener listener) {
    listeners.addElement(listener);
  }
  
  public boolean removeListener(LazyReaderListener listener) {
    return listeners.remove(listener);
  }
  
  public void notifyListeners(String line) {
    for(LazyReaderListener listener : listeners) {
      listener.handleReadLine(this, line);
    }
  }
  
  public void run() {
    String line;
    try {
      while((line = reader.readLine()) != null) {
        notifyListeners(line);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
}
